import 'dart:io';

import 'package:flutter/material.dart';
import 'package:tencent_cloud_chat_demo/db/custom_sticker_entity.dart';
import 'package:tencent_cloud_chat_demo/utils/api/sticker.dart';
import 'package:tencent_cloud_chat_demo/utils/path.dart';
import 'package:tencent_cloud_chat_demo/utils/toast.dart';
import 'package:tencent_cloud_chat_sdk/manager/v2_tim_manager.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_msg_create_info_result.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_value_callback.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_chat_global_model.dart';
import 'package:tencent_cloud_chat_uikit/data_services/message/message_services.dart';
import 'package:tencent_cloud_chat_uikit/data_services/services_locatar.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/ui/controller/tim_uikit_chat_controller.dart';

import 'emojis.dart';

class CustomStickerPannel extends StatefulWidget {
  const CustomStickerPannel({
    Key? key,
    required this.stickerImages,
    required this.pickImage,
    required this.chatController,
    this.width,
    this.userID,
    this.groupID,
    required this.deleteSticker,
  }) : super(key: key);

  final List<Emoji> stickerImages;

  final Future<void> Function() pickImage;

  final double? width;

  final String? userID;

  final String? groupID;

  final TIMUIKitChatController chatController;

  final Future<void> Function(List<int> ids) deleteSticker;

  @override
  State<StatefulWidget> createState() => _CustomStickerPannel();
}

class Emojis {
  final bool isEdit;
  final List<Emoji> emojis;
  final List<int> selects;

  Emojis({required this.isEdit, required this.emojis, required this.selects});
}

class _CustomStickerPannel extends State<CustomStickerPannel> {
  int selectIdx = 0;

  final MessageService _messageService = serviceLocator<MessageService>();

  final V2TIMManager sdkInstance = TIMUIKitCore.getSDKInstance();

  final ValueNotifier<Emojis> emojisNotifier = ValueNotifier(Emojis(
    emojis: [],
    isEdit: false,
    selects: [],
  ));

  bool isEdit = false;

  List<int> selectIndexs = [];

  int currentTab = 0;

  _tabs() {
    return Row(
      children: [
        GestureDetector(
          onTap: () {
            if (currentTab == 0) return;
            setState(() {
              currentTab = 0;
            });
          },
          child: Image.asset(
            "assets/sticker/emoji_menu.png",
            width: 45,
            height: 25,
            fit: BoxFit.contain,
          ),
        ),
        const Padding(padding: EdgeInsets.only(left: 5)),
        GestureDetector(
          onTap: () {
            if (currentTab == 1) return;
            setState(() {
              currentTab = 1;
            });
          },
          child: Image.asset(
            "assets/sticker/collect_menu.png",
            width: 35,
            height: 25,
            fit: BoxFit.contain,
            color: Colors.red,
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      emojisNotifier.value = Emojis(
        isEdit: isEdit,
        emojis: widget.stickerImages,
        selects: selectIndexs,
      );
    });
    return SizedBox(
      width: widget.width ?? 350,
      child: Column(
        children: [
          Container(
            decoration: const BoxDecoration(
              color: Colors.transparent, // 可选背景
              border: Border(
                bottom: BorderSide(
                  color: Colors.grey, // 边框颜色
                  width: 1, // 边框宽度
                ),
              ),
            ),
            child: Container(
              margin: const EdgeInsets.only(left: 10, bottom: 6, top: 6),
              child: _tabs(),
            ),
          ),
          const SizedBox(
            height: 8,
          ),
          if (currentTab == 0)
            Container(
              height: 200,
              padding: const EdgeInsets.fromLTRB(
                10,
                0,
                10,
                0,
              ),
              child: GridView.count(
                crossAxisCount: 8, // 一行 8 个
                mainAxisSpacing: 4, // 上下间距
                crossAxisSpacing: 4, // 左右间距
                childAspectRatio: 1, // 子元素宽高比 1:1（正方形）
                shrinkWrap: true, // 自动包裹内容（不会撑满）
                // physics: NeverScrollableScrollPhysics(), // 禁止内部滚动（可选）
                children: List.generate(allEmojis.length, (index) {
                  final emoji = allEmojis[index];
                  return GestureDetector(
                    onTap: () async {
                      // 点击事件
                      // print('点击了: ${emoji}');
                      V2TimValueCallback<V2TimMsgCreateInfoResult>
                          createImageMessageRes = await sdkInstance
                              .v2TIMMessageManager
                              .createTextMessage(text: emoji);
                      if (createImageMessageRes.code == 0) {
                        final messageInfo =
                            createImageMessageRes.data?.messageInfo;
                        if (messageInfo != null) {
                          widget.chatController.sendMessage(
                            messageInfo: messageInfo,
                            userID: widget.userID,
                            groupID: widget.groupID,
                            convType: widget.userID != null
                                ? ConvType.c2c
                                : ConvType.group,
                          );
                        }
                      }
                    },
                    child: Center(
                      child: Text(
                        emoji,
                        style: TextStyle(
                          fontSize: 28,
                        ),
                      ),
                    ),
                  );
                }),
              ),
            ),
          if (currentTab == 1)
            Container(
              padding: const EdgeInsets.fromLTRB(
                10,
                0,
                10,
                0,
              ),
              height: 200,
              child: GridView.count(
                crossAxisCount: 5, // 每行 4 个
                shrinkWrap: true, // 如果放在滚动容器中，避免无限高度
                // physics: const NeverScrollableScrollPhysics(), // 禁止内部滚动
                mainAxisSpacing: 8,
                crossAxisSpacing: 8,
                childAspectRatio: 1, // 宽高比为 1，搭配 80x80 使用
                children: List.generate(
                  widget.stickerImages.length + 1,
                  (index) {
                    if (index == 0) {
                      return GestureDetector(
                        onTap: () async {
                          await showModalBottomSheet(
                            useRootNavigator: true, // 关键点，确保使用最外层的 Navigator
                            isScrollControlled: true, // 允许撑满高度
                            context: context,
                            backgroundColor: Colors.transparent, // 透明背景才能自定义圆角
                            builder: (context) {
                              return ValueListenableBuilder<Emojis>(
                                valueListenable: emojisNotifier,
                                builder: (context, emojis, _) {
                                  return GestureDetector(
                                    onHorizontalDragEnd: (details) {
                                      if (details.primaryVelocity != null &&
                                          details.primaryVelocity! > 0) {
                                        // 用户从左往右滑（右滑）
                                        Navigator.pop(context);
                                      }
                                    },
                                    child: Container(
                                      padding: const EdgeInsets.all(16),
                                      decoration: const BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.vertical(
                                            top: Radius.circular(20)),
                                      ),
                                      child: Column(
                                        children: [
                                          const SizedBox(height: 32),
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            children: [
                                              GestureDetector(
                                                onTap: () {
                                                  Navigator.pop(context);
                                                },
                                                child: Image.asset(
                                                  'assets/sticker/back.png',
                                                  width: 26,
                                                  height: 26,
                                                  fit: BoxFit.contain,
                                                ),
                                              ),
                                              Text(
                                                '添加的表情(${emojis.emojis.length})',
                                                style: const TextStyle(
                                                  fontSize: 16,
                                                  color: Colors.black,
                                                  fontWeight: FontWeight.w600,
                                                ),
                                              ),
                                              GestureDetector(
                                                child: Text(
                                                  !isEdit ? '整理' : '取消',
                                                  style: const TextStyle(
                                                    fontSize: 16,
                                                    color: Colors.black,
                                                    fontWeight: FontWeight.w600,
                                                  ),
                                                ),
                                                onTap: () {
                                                  setState(() {
                                                    isEdit = !isEdit;
                                                  });
                                                },
                                              ),
                                            ],
                                          ),
                                          const SizedBox(height: 12),
                                          Expanded(
                                            child: Stack(
                                              fit: StackFit.expand,
                                              children: [
                                                GridView.count(
                                                  crossAxisCount: 4, // 每行 4 个
                                                  shrinkWrap:
                                                      true, // 如果放在滚动容器中，避免无限高度
                                                  // physics: const NeverScrollableScrollPhysics(), // 禁止内部滚动
                                                  mainAxisSpacing: 8,
                                                  crossAxisSpacing: 8,
                                                  childAspectRatio:
                                                      1, // 宽高比为 1，搭配 80x80 使用
                                                  children: List.generate(
                                                    emojis.emojis.length + 1,
                                                    (index) {
                                                      if (index == 0) {
                                                        return GestureDetector(
                                                          onTap: () async {
                                                            await widget
                                                                .pickImage();
                                                          },
                                                          child: Container(
                                                            width: 80,
                                                            height: 80,
                                                            decoration:
                                                                BoxDecoration(
                                                              color: Colors
                                                                  .grey[200],
                                                              borderRadius:
                                                                  const BorderRadius
                                                                      .vertical(
                                                                top: Radius
                                                                    .circular(
                                                                        8),
                                                                bottom: Radius
                                                                    .circular(
                                                                        8),
                                                              ),
                                                            ),
                                                            child: Center(
                                                              child:
                                                                  Image.asset(
                                                                'assets/sticker/add.png',
                                                                width: 24,
                                                                height: 24,
                                                              ),
                                                            ),
                                                          ),
                                                        );
                                                      }
                                                      return GestureDetector(
                                                        onTap: () {
                                                          if (isEdit) {
                                                            if (selectIndexs
                                                                .contains(
                                                                    index)) {
                                                              setState(() {
                                                                selectIndexs
                                                                    .remove(
                                                                        index);
                                                              });
                                                            } else {
                                                              setState(() {
                                                                selectIndexs
                                                                    .add(index);
                                                              });
                                                            }
                                                          }
                                                        },
                                                        child: Stack(
                                                          children: [
                                                            Container(
                                                              width: 80,
                                                              height: 80,
                                                              padding:
                                                                  const EdgeInsets
                                                                      .all(6),
                                                              decoration:
                                                                  BoxDecoration(
                                                                color: Colors
                                                                    .grey[200],
                                                                borderRadius:
                                                                    const BorderRadius
                                                                        .vertical(
                                                                  top: Radius
                                                                      .circular(
                                                                          8),
                                                                  bottom: Radius
                                                                      .circular(
                                                                          8),
                                                                ),
                                                              ),
                                                              child: Center(
                                                                child:
                                                                    Image.file(
                                                                  File(AppPath.resolveEmojiPath(emojis
                                                                      .emojis[
                                                                          index -
                                                                              1]
                                                                      .keywords)),
                                                                  fit: BoxFit
                                                                      .cover,
                                                                ),
                                                              ),
                                                            ),
                                                            Positioned(
                                                              child: Visibility(
                                                                visible: isEdit &&
                                                                    !selectIndexs
                                                                        .contains(
                                                                            index),
                                                                child:
                                                                    Image.asset(
                                                                  "assets/icons/uncheck.png",
                                                                  width: 18,
                                                                ),
                                                              ),
                                                              top: 5,
                                                              right: 5,
                                                            ),
                                                            Positioned(
                                                              child: Visibility(
                                                                visible: isEdit &&
                                                                    selectIndexs
                                                                        .contains(
                                                                            index),
                                                                child:
                                                                    Image.asset(
                                                                  width: 18,
                                                                  "assets/icons/check.png",
                                                                ),
                                                              ),
                                                              top: 5,
                                                              right: 5,
                                                            ),
                                                          ],
                                                        ),
                                                      );
                                                    },
                                                  ),
                                                ),
                                                Visibility(
                                                  visible: isEdit,
                                                  child: Positioned(
                                                    bottom: 40,
                                                    left:
                                                        (MediaQuery.of(context)
                                                                    .size
                                                                    .width /
                                                                2) -
                                                            64,
                                                    child: GestureDetector(
                                                      onTap: () async {
                                                        final List<int> ids =
                                                            selectIndexs
                                                                .map((s) => emojis
                                                                    .emojis[
                                                                        s - 1]
                                                                    .fileId)
                                                                .toList();
                                                        await widget
                                                            .deleteSticker(
                                                          ids,
                                                        );
                                                        ToastUtils.toast(
                                                            '表情删除成功');
                                                        setState(() {
                                                          selectIndexs.clear();
                                                        });
                                                      },
                                                      child: Container(
                                                          padding:
                                                              const EdgeInsets
                                                                  .fromLTRB(
                                                            32,
                                                            8,
                                                            32,
                                                            8,
                                                          ),
                                                          decoration:
                                                              BoxDecoration(
                                                            color: Colors.black,
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        20),
                                                          ),
                                                          child: const Text(
                                                            '删除',
                                                            style: TextStyle(
                                                                color: Colors
                                                                    .white,
                                                                fontSize: 16),
                                                          )),
                                                    ),
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              );
                            },
                          );
                          isEdit = false;
                          selectIndexs = [];
                        },
                        child: Container(
                          width: 80,
                          height: 80,
                          decoration: BoxDecoration(
                            color: Colors.grey[200],
                            borderRadius: const BorderRadius.vertical(
                              top: Radius.circular(8),
                              bottom: Radius.circular(8),
                            ),
                          ),
                          child: Center(
                            child: Image.asset(
                              'assets/sticker/add.png',
                              width: 24,
                              height: 24,
                            ),
                          ),
                        ),
                      );
                    }
                    return GestureDetector(
                      onTap: () async {
                        V2TimValueCallback<V2TimMsgCreateInfoResult>
                            createImageMessageRes = await sdkInstance
                                .v2TIMMessageManager
                                .createImageMessage(
                          imagePath: AppPath.resolveEmojiPath(
                              widget.stickerImages[index - 1].keywords),
                          imageName: widget.stickerImages[index - 1].keywords,
                        );
                        if (createImageMessageRes.code == 0) {
                          String id = createImageMessageRes.data?.id ?? '';

                          final messageInfo =
                              createImageMessageRes.data?.messageInfo;
                          if (messageInfo != null) {
                            widget.chatController.sendMessage(
                              cloudCustomData: 'custom_sticker',
                              messageInfo: messageInfo,
                              userID: widget.userID,
                              groupID: widget.groupID,
                              convType: widget.userID != null
                                  ? ConvType.c2c
                                  : ConvType.group,
                            );
                          }

                          // V2TimValueCallback<V2TimMessage> sendMsgRes =
                          //     await _messageService.sendMessage(
                          //   id: id,
                          //   receiver: widget.userID ?? '',
                          //   groupID: widget.groupID ?? '',
                          // );

                          // if (sendMsgRes.code == 0) {
                          //   // 发送成功
                          //   widget.chatController.refreshCurrentHistoryList();
                          // }
                        }
                      },
                      child: SizedBox(
                        width: 80,
                        height: 80,
                        child: Center(
                          child: Image.file(
                            File(AppPath.resolveEmojiPath(
                                widget.stickerImages[index - 1].keywords)),
                            fit: BoxFit.fitHeight,
                          ),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
        ],
      ),
    );
  }
}
